package com.chen.common.satoken.component;

import cn.dev33.satoken.stp.StpInterface;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.chen.base.module.mybatis.mapper.CommonMapper;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 自定义权限加载接口实现类
 * 保证此类被 SpringBoot 扫描，完成 Sa-Token 的自定义权限验证扩展
 * @author ChenJinLong
 */
@Component
public class StpInterfaceImpl implements StpInterface {

    @Resource
    private CommonMapper commonMapper;

    /**
     * 返回一个账号所拥有的权限码集合
     */
    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        Set<Long> roleIds = getRoleIds(loginId);

        List<String> list = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(roleIds)){
            String sql = StrUtil.format("select permission_id from auth_link_role_permission where role_id in ({})",
                    CollectionUtil.join(roleIds, ","));
            List<String> authRoles = commonMapper.getSinColumnList(sql);
            List<Long> perIdList = authRoles.stream().map(Long::valueOf).collect(Collectors.toList());

            if (CollectionUtil.isNotEmpty(perIdList)){
                sql = StrUtil.format("select code from auth_permission where permission_id in ({})",
                        CollectionUtil.join(perIdList, ","));
                list = commonMapper.getSinColumnList(sql);
            }
        }

        return list;
    }

    /**
     * 返回一个账号所拥有的角色标识集合 (权限与角色可分开校验)
     */
    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        Set<Long> roleIds = getRoleIds(loginId);

        List<String> list = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(roleIds)){
            String sql = StrUtil.format("select role_code from auth_role where role_id in ({})",
                    CollectionUtil.join(roleIds, ","));
            list = commonMapper.getSinColumnList(sql);
        }

        return list;
    }

    private Set<Long> getRoleIds(Object loginId) {
        String sql = StrUtil.format("select role_id from auth_link_user_role where user_id = {}", loginId);
        List<String> list = commonMapper.getSinColumnList(sql);
        return list.stream().map(Long::valueOf).collect(Collectors.toSet());
    }
}
